package com.tarena.lbs.basic.web.service;

import com.alibaba.nacos.common.utils.CollectionUtils;
import com.github.pagehelper.PageInfo;
import com.tarena.lbs.base.common.utils.Asserts;
import com.tarena.lbs.base.protocol.exception.BusinessException;
import com.tarena.lbs.base.protocol.pager.PageResult;
import com.tarena.lbs.basic.web.dao.repository.AdminRepository;
import com.tarena.lbs.basic.web.dao.repository.BusinessRepository;
import com.tarena.lbs.basic.web.thread.AuthenticationUtil;
import com.tarena.lbs.common.passport.enums.Roles;
import com.tarena.lbs.common.passport.principle.UserPrinciple;
import com.tarena.lbs.common.security.utils.LbsSecurityContenxt;
import com.tarena.lbs.pojo.basic.dto.AdminDTO;
import com.tarena.lbs.pojo.basic.param.AdminParam;
import com.tarena.lbs.pojo.basic.po.AdminPO;
import com.tarena.lbs.pojo.basic.po.BusinessPO;
import com.tarena.lbs.pojo.basic.query.AdminQuery;
import com.tarena.lbs.pojo.basic.vo.AdminVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class AdminService {
    @Autowired
    private AdminRepository adminRepository;
    @Autowired
    private BusinessRepository businessRepository;
    public AdminVO detail() throws BusinessException {
        //作为过滤器的执行代码的下游逻辑 可以直接在threadLocal获取数据
        //在业务层获取到的数据 就是本次请求的认证对象
        UserPrinciple userPrinciple=getAuthentication();
        //不一定能拿到认证对象 抛异常
        Asserts.isTrue(userPrinciple==null,new BusinessException("-2","认证解析失败"));
        Integer id = userPrinciple.getId();
        //1.查询adminPO
        AdminPO po = adminRepository.getById(id);
        AdminVO vo=null;
        if (po!=null){
            vo=new AdminVO();
            BeanUtils.copyProperties(po,vo);
        }
        return vo;
    }
    public AdminDTO detail(Integer adminId)throws BusinessException{
        AdminPO po = adminRepository.getById(adminId);
        AdminDTO dto=null;
        if (po!=null){
            dto=new AdminDTO();
            BeanUtils.copyProperties(po,dto);
        }
        return dto;
    }


    private UserPrinciple getAuthentication() {
        return AuthenticationUtil.get();
    }

    public PageResult<AdminVO> adminPage(AdminQuery query) {
        //1.使用条件查询仓储层pageInfo
        PageInfo<AdminPO> poPageInfo= adminRepository.getAdminByPage(query);
        //2.封装pageResult pageNo pageSize total object(分页数据)
        PageResult<AdminVO> voPages=new PageResult<>();
        voPages.setPageNo(poPageInfo.getPageNum());
        voPages.setPageSize(poPageInfo.getPageSize());
        voPages.setTotal(poPageInfo.getTotal());
        List<AdminVO> vos=null;
        if (CollectionUtils.isNotEmpty(poPageInfo.getList())){
            //stream()
            vos=poPageInfo.getList().stream().map(po->{
                AdminVO vo=new AdminVO();
                BeanUtils.copyProperties(po,vo);
                return vo;
            }).collect(Collectors.toList());
        }
        voPages.setObjects(vos);
        return voPages;
    }
    public void adminSave(AdminParam param) throws BusinessException {
        checkRole(Roles.ADMIN);
        //判断校验businessId商家是否存在
        checkBusinessExists(param);
        //1.幂等 新增insert 先查 后增(也可以将手机号 email做成唯一字段 try catch数据异常)
        Long total=adminRepository.countByPhoneOrEmail(param);
        Asserts.isTrue(total>0,new BusinessException("-2","手机号或邮箱已存在"));
        //2.补充数据新增
        AdminPO poParam=new AdminPO();
        BeanUtils.copyProperties(param,poParam);
        poParam.setAccountStatus(0);//启用0  禁用1
        poParam.setBusinessId(param.getAccountType()==0?0:param.getBusinessId());
        poParam.setCreateTime(new Date());
        adminRepository.saveAdmin(poParam);
    }

    private void checkBusinessExists(AdminParam param) throws BusinessException {
        if (param.getAccountType()==1) {//新增的是一个商家账号
            BusinessPO poBiz = businessRepository.getBusiness(param.getBusinessId());
            Asserts.isTrue(poBiz == null, new BusinessException("-2", "商家不存在"));
        }
    }

    private void checkRole(Roles roles) throws BusinessException {
        //直接使用断言,当前登录的用户角色 和业务需要得用户角色不相等 断言命中 抛异常
        UserPrinciple userPrinciple = AuthenticationUtil.get();
        Asserts.isTrue(userPrinciple==null,new BusinessException("-2","用户解析认证失败"));
        //获取登录用户的角色
        Roles loginRole=userPrinciple.getRole();
        Asserts.isTrue(loginRole!=roles,new BusinessException("-2","权限不足"));
    }
}
